package com.china08.yxyapi.api.home.resource;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.yxyresource.YxyResourceService;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.FloatUtil;
import com.china08.yxyapi.util.YxyResUtil;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class ResourceController extends YxyApiBaseController {

    @Autowired
    private YxyResUtil YxyResUtil;

    @Autowired
    private YxyResourceService yrs;

    @Autowired
    private YxyResBookRepository yxyResBookRepository;

    @ApiOperation(value = "首页资源查询")
    @ResponseBody
    @RequestMapping(value = "/api_yw/home/res/lst", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> find(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqModel reqModel) throws IllegalAccessException, InvocationTargetException {
        Page<RespModel> respPage = null;
        YxyResBook book = yxyResBookRepository.findById(reqModel.bookId);
        String phase = book.getPhaseId();
        String subject = book.getSubjectId();
        String version = book.getVersionId();
        String bookcontent = reqModel.bookcontent;
        String semester = book.getSemersterId();
        String bookId = reqModel.bookId;
        String type = reqModel.type;
        String format = reqModel.format;
        String keyword = reqModel.keyword;
        // ## pageable
        Pageable pageable = null;
        if (StringUtils.isNotBlank(reqModel.keyword)) {
            keyword = keyword.toLowerCase();
            pageable = new PageRequest(reqModel.page, reqModel.size);
        } else {
            pageable = reqModel.getPageable(Direction.fromString(reqModel.order), reqModel.field);
        }
        List<RespModel> list = new ArrayList<ResourceController.RespModel>();
        Page<ElasticYxyResResource> page = null;

        YxyProfile yxyProfile = getProfile(request, response);
        String userId = yxyProfile != null ? yxyProfile.getId() : "";

        // 1.
        if (reqModel.resType == 1) {
            String areaId = reqModel.areaId;
            page = yrs.homeIndexResourceArea(areaId, reqModel.resType, phase, subject, version, bookcontent, semester,
                    bookId, type, format, keyword, Type.PHRASE, pageable);
        } else if (reqModel.resType == 2) {
            String schoolId = reqModel.schoolId;
            page = yrs.homeIndexResourceSchool(schoolId, reqModel.resType, phase, subject, version, bookcontent,
                    semester, bookId, type, format, keyword, Type.PHRASE, pageable);
        } else if (reqModel.resType == 3) {
            page = yrs.homeIndexResourceYun(reqModel.resType, phase, subject, version, bookcontent, semester, bookId,
                    type, format, keyword, Type.PHRASE, reqModel.flag, reqModel.typeres, pageable);
        }
        //
        long totle = 0l;
        if (page != null) {
            totle = page.getTotalElements();
            for (ElasticYxyResResource elasticYxyResResource : page) {
                RespModel model = new RespModel();
                BeanUtils.copyProperties(model, elasticYxyResResource);
                if (elasticYxyResResource.getUploadTime() != null) {
                    model.uploadTimeFormat = DateToolUtils.format(elasticYxyResResource.getUploadTime(),
                            DateToolUtils.FORMAT_SHORT_YMD);
                }
                model.isFavor = 0;
                if (StringUtils.isNotBlank(userId)) {
                    model.isFavor = yrs.checkFavor(userId, null, "ROLE_TEACHER", elasticYxyResResource.getId()) > 0 ? 1
                            : 0;
                }
                model.setMark(FloatUtil.dot1(elasticYxyResResource.getMark()));
                String download = YxyResUtil.getDownloadUrl(elasticYxyResResource.getId());
                model.setDownloadLocation(download);
                list.add(model);
            }
        }

        respPage = new PageImpl<>(list, pageable, totle);
        return respPage;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        // 1区域资源 2本校资源 3云校资源
        public Integer resType = 1;
        // 域名
        public String areaId;
        public String phase;
        public String subject;
        public String version;
        public String bookcontent;
        public String semester;
        public String bookId;
        public String type;
        public String format;
        public String keyword;
        public String field = "uploadTime";
        public String order = "desc";
        public String schoolId;
        // 0 不限 1 vip 2 免费
        public Integer flag = 0;
        // 0 精品资源 1 普通资源 2不限
        public Integer typeres = 2;

    }

    public static class RespModel extends YxyApiRespModel {
        // 资源ID
        public String id;

        // 资源作者
        public String author;

        // 上传人名
        public String uploaderName;

        // 上传者学校名字
        public String uploaderSchoolName;

        // 资源简介
        public String intro;

        // 标题
        public String title;

        // 文件大小
        public Integer fileSize = 0;

        // 文件扩展名
        public String extension;

        // 下载量
        public Long downloadCount = 0l;

        // 浏览次数
        public Long pv = 0l;

        // 收藏次数
        public Long favoriteCount = 0l;

        public Integer isDelete = 0;

        // 文件的状态信息 0初始上传， 1 转码中 ，2 转码成功 ，3 转码失败
        public Integer convertStatus = 0;

        // 文件路径
        public String location;

        // 评分
        public float mark = 0f;

        // 上传时间
        public String uploadTimeFormat = "";

        // 格式
        public String formatId;

        // 是否收藏 0否 1是
        public Integer isFavor = 0;

        // 下载连接
        public String downloadLocation = "";

        // 类型
        public String typeId;

        public Boolean isVip = false;

        public Integer isHighQualityYx = 0;

        public Boolean getIsVip() {
            return isVip;
        }

        public void setIsVip(Boolean isVip) {
            this.isVip = isVip;
        }

        public Integer getIsHighQualityYx() {
            return isHighQualityYx;
        }

        public void setIsHighQualityYx(Integer isHighQualityYx) {
            this.isHighQualityYx = isHighQualityYx;
        }

        public String getUploadTimeFormat() {
            return uploadTimeFormat;
        }

        public void setUploadTimeFormat(String uploadTimeFormat) {
            this.uploadTimeFormat = uploadTimeFormat;
        }

        public Integer getIsFavor() {
            return isFavor;
        }

        public void setIsFavor(Integer isFavor) {
            this.isFavor = isFavor;
        }

        public String getTypeId() {
            return typeId;
        }

        public void setTypeId(String typeId) {
            this.typeId = typeId;
        }

        public String getDownloadLocation() {
            return downloadLocation;
        }

        public void setDownloadLocation(String downloadLocation) {
            this.downloadLocation = downloadLocation;
        }

        /*
         * public Integer getIsFavor() { return isFavor; }
         * 
         * public void setIsFavor(Integer isFavor) { this.isFavor = isFavor; }
         */

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getUploaderName() {
            return uploaderName;
        }

        public void setUploaderName(String uploaderName) {
            this.uploaderName = uploaderName;
        }

        public String getUploaderSchoolName() {
            return uploaderSchoolName;
        }

        public void setUploaderSchoolName(String uploaderSchoolName) {
            this.uploaderSchoolName = uploaderSchoolName;
        }

        public String getIntro() {
            return intro;
        }

        public void setIntro(String intro) {
            this.intro = intro;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Integer getFileSize() {
            return fileSize;
        }

        public void setFileSize(Integer fileSize) {
            this.fileSize = fileSize;
        }

        public String getExtension() {
            return extension;
        }

        public void setExtension(String extension) {
            this.extension = extension;
        }

        public Long getDownloadCount() {
            return downloadCount;
        }

        public void setDownloadCount(Long downloadCount) {
            this.downloadCount = downloadCount;
        }

        public Long getPv() {
            return pv;
        }

        public void setPv(Long pv) {
            this.pv = pv;
        }

        public Long getFavoriteCount() {
            return favoriteCount;
        }

        public void setFavoriteCount(Long favoriteCount) {
            this.favoriteCount = favoriteCount;
        }

        public Integer getIsDelete() {
            return isDelete;
        }

        public void setIsDelete(Integer isDelete) {
            this.isDelete = isDelete;
        }

        public Integer getConvertStatus() {
            return convertStatus;
        }

        public void setConvertStatus(Integer convertStatus) {
            this.convertStatus = convertStatus;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public float getMark() {
            return mark;
        }

        public void setMark(float mark) {
            this.mark = mark;
        }

        public String getFormatId() {
            return formatId;
        }

        public void setFormatId(String formatId) {
            this.formatId = formatId;
        }

    }
}
